import React, {
    useEffect,
    useLayoutEffect,
    useState,
} from "react"
import { DatePicker, ConfigProvider, Radio, Checkbox, Upload, Select, message, DatePickerProps } from "antd"
import fetch from "../../../util/fetch"
import CONFIG from "../../../util/ipConfig"
import Cropper from "../../../component/cropper"
import $ from "jquery"
import zhCN from "antd/es/locale/zh_CN"
import Scrollbars from "react-custom-scrollbars"
import { fileIcon } from "../../../util/public"
import momoent from "moment"
import "./index.scss"
const { Option } = Select
const {
    BasicProxy
} = CONFIG
const { RangePicker } = DatePicker
/**
 * 公共传参：
 * type: 选项输入类型  date/time/input/textarea/radio/checkbox/dropMenu/logo/image/file/search
 * optionName: 选项名称
 * value: 选项值
 * className: 选项容器类名
 * getVal: 获取值的函数
 * 
 * type: logo、image、file上传文件
 * 
 */
function ModalOption (props) {
    let {
        type,
        optionName,
        value,
        className,
        textStyle
    } = props
    if (type === "input") {
        return (
            <OptionInput {...props} />
        )
    }
    if (type === "textarea") {
        return (
            <OptionTextarea {...props} />
        )
    }
    if (type === "search") {
        return (
            <OptionSearch {...props} />
        )
    }
    if (type === "dateRange") {
        return (
            <OptionDateRange {...props} />
        )
    }
    if (type === "date") {
        return (
            <OptionDate {...props} />
        )
    }
    if (type === "time") {
        return (
            <OptionTime {...props} />
        )
    }
    if (type === "radio") {
        return (
            <OptionRadio {...props} />
        )
    }
    if (type === "checkbox") {
        return (
            <OptionCheckBox {...props} />
        )
    }
    if (type === "dropMenu") {
        return (
            <OptionDropMenu {...props} />
        )
    }
    if (type === "logo") {
        return (
            <OptionLogo {...props} />
        )
    }
    if (type === "image") {
        return (
            <OptionImage {...props} />
        )
    }
    if (type === "file") {
        return (
            <OptionFile {...props} />
        )
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">{optionName}:</span>
            <span className="option_value" style={textStyle} title={value ? value : `暂无${optionName}信息`}>{value ? value : `暂无${optionName}信息`}</span>
        </div>
    )

}

/**
 * type: input、textarea:
 * placeholder: 默认值，选项为input/textarea有效
 * width: input/textarea的宽度
 * maxLength: 最大长度
 * 
*/
//搜索框
function OptionSearch (props) {
    let {
        className,
        optionName,
        placeholder,
        maxLength,
        value,
        getVal,
        width,
        optional,
        userType
    } = props
    const [keyword, setKeyword] = useState("")
    const [searchList, setSearchList] = useState([])
    const [showData, setShowData] = useState("")
    const [forceHidden, setForceHidden] = useState(true)
    //搜索用户
    const goSearch = () => {
        let url = window.BasicProxy + "api/common/user/searchUser"
        fetch
            .get({
                url, params: {
                    schoolId: sessionStorage.getItem("schoolId"),
                    userName: keyword,
                    size: 10,
                    page: -1,
                }
            })
            .then((res) => res.json())
            .then((res) => {
                console.log(userType)
                if (res.code == 200 && Array.isArray(res.data)) {
                    if (userType) {
                        let list = res.data.filter((item) => {
                            return userType.indexOf(item.userType) !== -1
                        })
                        console.log(list)
                        setSearchList(list)
                        return
                    }
                    setSearchList(res.data)
                }
            })
    }
    const changeValue = (e) => {
        console.log(e.target.value)
        let value = e.target.value
        setKeyword(value)
        // goSearch()
        setForceHidden(false)
    }
    const chooseOption = (data) => {
        if (data.AvatarPath) {
            data.PhotoPath = data.AvatarPath
        }
        typeof getVal === "function" &&
            getVal(data)
        setShowData(data.UserName || data.userName)
        setForceHidden(true)
    }
    useEffect(() => {
        goSearch()
    }, [keyword])
    useEffect(() => {
        window.addEventListener("click", function (e) {
            let target = $(e.target)
            if (
                target.attr("class") !== "show_selected" &&
                target.attr("class") !== "list_one" &&
                target.parent().attr("class") !== "search_list") {
                setForceHidden(true)
            }
        })
    }, [])
    useLayoutEffect(() => {
        if (!value || typeof value !== "object") {
            setKeyword("")
            setShowData("")
            return
        }
        setShowData(value.UserName || value.userName)
        setForceHidden(true)
    }, [value])
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <span className="show_selected" style={{
                width
            }} title={showData} onClick={() => setForceHidden(!forceHidden)}>{showData ? showData : "未选择"}</span>
            {
                !forceHidden ?
                    <div className="option_search_container" style={{
                        width,
                        left: $(".option_name").width() + 8
                    }}>
                        <div className="search_list">
                            <input
                                className="option_search"
                                type="text"
                                value={keyword}
                                onChange={changeValue}
                                placeholder={placeholder}
                                maxLength={maxLength ? maxLength : 50} />
                            <i className="searchlogo"></i>
                            <Scrollbars autoHeight autoHeightMax={120}>
                                {
                                    searchList.length > 0 ?
                                        searchList.map((item, index) => {
                                            return (
                                                <div
                                                    className="list_one"
                                                    key={index}
                                                    onClick={() => chooseOption(item)}
                                                    title={`${item.UserName || item.userName}(${item.UserID || item.userID || item.userId})`}>
                                                    {item.UserName || item.userName}
                                                    <span style={{ color: "#999" }}>({item.UserID || item.userID || item.userId})</span>
                                                </div>
                                            )
                                        }) :
                                        <p className="search_empty_text">暂无搜索结果~</p>
                                }
                            </Scrollbars>
                        </div>
                    </div> :
                    ""
            }
        </div>
    )
}
//输入框
function OptionInput (props) {
    let {
        className,
        optionName,
        placeholder,
        maxLength,
        value,
        getVal,
        width,
        disabled,
        optional
    } = props
    const filteremoji = (str) => {
        var ranges = [
            '\ud83c[\udf00-\udfff]',
            '\ud83d[\udc00-\ude4f]',
            '\ud83d[\ude80-\udeff]'
        ]
        str = str.replace(new RegExp(ranges.join('|'), 'g'), '')
        return str
    }
    const changeValue = (e) => {
        let value = e.target.value
        typeof getVal === "function" &&
            getVal(filteremoji(value))
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <input
                className="option_input"
                type="text"
                value={value}
                style={{ width, paddingRight: (value && maxLength ? 40 : "") }}
                disabled={disabled}
                onChange={changeValue}
                placeholder={placeholder}
                maxLength={maxLength ? maxLength : 50} />
            {
                value && maxLength ?
                    <span className="option_input_count">{`${value.length}/${maxLength}`}</span> :
                    ""
            }
        </div>
    )
}
//文本域
function OptionTextarea (props) {
    let {
        className,
        optionName,
        placeholder,
        maxLength,
        width,
        height,
        value,
        getVal,
        disabled,
        optional
    } = props
    const filteremoji = (str) => {
        var ranges = [
            '\ud83c[\udf00-\udfff]',
            '\ud83d[\udc00-\ude4f]',
            '\ud83d[\ude80-\udeff]'
        ]
        str = str.replace(new RegExp(ranges.join('|'), 'g'), '')
        return str
    }
    const changeValue = (e) => {
        let value = e.target.value
        typeof getVal === "function" &&
            getVal(filteremoji(value))
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <textarea
                className="option_textarea"
                style={{ width, height }}
                disabled={disabled}
                value={value}
                onChange={changeValue}
                placeholder={placeholder}
                maxLength={maxLength ? maxLength : 200} />
            {
                value && maxLength ?
                    <span className="option_textarea_count">{`${value.length}/${maxLength}`}</span> :
                    ""
            }
        </div>
    )
}

/**
 * type: date:
 * showTime: 显示时分选择
 * format: 格式化时间
 * min: 可选最小时间
 * max: 可选最大时间
 */
//日期选择框
function OptionDate (props) {
    let {
        className,
        optionName,
        value,
        getVal,
        showTime,
        format,
        min,
        max,
        disabled,
        optional
    } = props
    const changeValue = (date1, date2) => {
        typeof getVal === "function" &&
            getVal(date2)
    }
    const setDisableDate = (current) => {
        console.log(momoent().endOf(min))
        if (min) {
            return current < momoent(min).endOf("day")
        }
        if (max) {
            return current > momoent(max).startOf("day")
        }
    }
    const range = (start, end) => {
        const result = []
        for (let i = start; i < end; i++) {
            result.push(i)
        }
        return result
    }
    const setDisableTime = (current) => {
        // console.log(current);
        if (min) {
            if (current < momoent(min)) {
                return {
                    disabledHours: () => range(0, 24),
                    disabledMinutes: () => range(0, 60)
                }
            }
            return false
        }
        if (max) {
            if (current > momoent(max)) {
                return {
                    disabledHours: () => range(0, 24),
                    disabledMinutes: () => range(0, 60)
                }
            }
            return false
        }
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <ConfigProvider locale={zhCN}>
                <DatePicker
                    showTime={true}
                    value={value ? momoent(value) : ""}
                    onChange={changeValue}
                    showNow={false}
                    // min={min}
                    // showTime={{ format: 'HH:mm' }}
                    disabledDate={setDisableDate}
                    disabledTime={setDisableTime}
                    format={"YYYY-MM-DD HH:mm"}
                // disabled={disabled}
                // getPopupContainer={(trigger) => trigger.parentElement}
                />
            </ConfigProvider>
        </div>
    )
}
//时分选择框
function OptionTime (props) {
    let {
        className,
        optionName,
        value,
        getVal,
        showTime,
        format,
        min,
        max,
        disabled,
        optional
    } = props
    const changeValue = (date1, date2) => {
        typeof getVal === "function" &&
            getVal(date2)
    }
    const setDisableDate = (current) => {
        if (min) {
            return current < momoent(min)
        }
        if (max) {
            return current > momoent(max)
        }
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <ConfigProvider locale={zhCN}>
                <DatePicker
                    showTime={"YYYY-MM-DD hh:ss"}
                    value={value ? momoent(value) : ""}
                    onChange={changeValue}
                    disabledDate={setDisableDate}
                    disabled={disabled}
                    format={format ? format : ""}
                    getPopupContainer={(trigger) => trigger.parentElement} />
            </ConfigProvider>
        </div>
    )
}
//日期范围选择框
function OptionDateRange (props) {
    let {
        className,
        optionName,
        value,
        getVal,
        showTime,
        format,
        min,
        max,
        disabled,
        optional
    } = props
    const changeValue = (dates) => {
        let arr = []
        if (!Array.isArray(dates)) {
            return
        }
        dates.forEach((item) => {
            arr.push(momoent(item).format("YYYY-MM-DD"))
        })
        typeof getVal === "function" &&
            getVal(arr)
    }
    const setDisableDate = (current) => {
        if (min && !max) {
            return current < momoent(min).endOf("day")
        }
        if (max && !min) {
            return current > momoent(max).startOf("day")
        }
        if (max && min) {
            return current < momoent(min).endOf("day") || current > momoent(max).startOf("day")
        }
    }
    const range = (start, end) => {
        const result = []
        for (let i = start; i < end; i++) {
            result.push(i)
        }
        return result
    }
    const setDisableTime = (current) => {
        // console.log(current);
        if (min) {
            if (current < momoent(min)) {
                return {
                    disabledHours: () => range(0, 24),
                    disabledMinutes: () => range(0, 60)
                }
            }
            return false
        }
        if (max) {
            if (current > momoent(max)) {
                return {
                    disabledHours: () => range(0, 24),
                    disabledMinutes: () => range(0, 60)
                }
            }
            return false
        }
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <ConfigProvider locale={zhCN}>
                <RangePicker
                    value={Array.isArray(value) ? value.map(item => momoent(item)) : ""}
                    onChange={changeValue}
                    // min={min}
                    disabledDate={setDisableDate}
                // disabledTime={setDisableTime}
                // format={"YYYY-MM-DD"}
                // disabled={disabled}
                // getPopupContainer={(trigger) => trigger.parentElement}
                />
            </ConfigProvider>
        </div>
    )
}
//单选框
function OptionRadio (props) {
    let {
        className,
        optionName,
        value,
        list,
        getVal,
        disabled,
        optional
    } = props
    const changeValue = (e) => {
        let value = e.target.value
        typeof getVal === "function" &&
            getVal(value)
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <Radio.Group onChange={changeValue} value={value} disabled={disabled}>
                {
                    Array.isArray(list) &&
                    list.map((item, index) => {
                        return (
                            <Radio key={index} value={item.key || item.id}>{item.name}</Radio>
                        )
                    })
                }
            </Radio.Group>
        </div>
    )
}
//复选框
function OptionCheckBox (props) {
    let {
        className,
        optionName,
        value,
        list,
        getVal,
        disabled,
        optional
    } = props
    const changeValue = (valueArr) => {
        typeof getVal === "function" &&
            getVal(valueArr)
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <Checkbox.Group onChange={changeValue} value={value} disabled={disabled}>
                {
                    Array.isArray(list) &&
                    list.map((item, index) => {
                        return (
                            <Checkbox key={index} value={item.key || item.id}>{item.name}</Checkbox>
                        )
                    })
                }
            </Checkbox.Group>
        </div>
    )
}
//下拉菜单
function OptionDropMenu (props) {
    let {
        className,
        optionName,
        disabled,
        value,
        list,
        getVal,
        width,
        style,
        tip,
        showBtnMethod,
        showBtn,
        optional
    } = props
    const changeValue = (value) => {
        if (value !== 0 && !value) {
            typeof showBtnMethod === "function" && showBtnMethod()
            return
        }
        let id = list[value].id || list[value].key
        typeof getVal === "function" &&
            getVal(id)
    }
    let name = "未选择"
    if (Array.isArray(list) && (value || typeof value === "boolean")) {
        list.forEach((item) => {
            if (item.key === value || item.id === value) {
                name = item.name
            }
        })
    }
    return (
        <div className={`info_option ${className ? className : ""}`} style={{ ...style }}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <ConfigProvider locale={zhCN}>
                <Select
                    defaultValue="未选择"
                    className={`option_select ${typeof value !== "number" && !value ? "default" : ""}`}
                    style={{ width }}
                    onChange={changeValue}
                    disabled={disabled}
                    listHeight={120}
                    value={name}
                    getPopupContainer={(trigger) => document.body}>
                    {/* <Option value="">未选择</Option>  */}
                    {
                        Array.isArray(list) &&
                        list.map((item, index) => {
                            return (
                                <Option key={index} value={index}>{item.name}</Option>
                            )
                        })
                    }
                    {
                        showBtn && showBtnMethod ?
                            showBtn :
                            ""
                    }
                </Select>
            </ConfigProvider>
            {/* {
            Array.isArray(list) &&
            list.length > 0?
            "":
            <p className="info_option_tip">(暂无数据，请联系管理员处理)</p>
        } */}
            {/* {
            tip?
            <span style={{marginLeft:10}}>({tip})</span>:
            ""
        } */}
        </div>
    )
}
//单个图片
function OptionLogo (props) {
    let {
        className,
        optionName,
        value,
        getVal,
        disabled,
        optional
    } = props
    const [logoInfo, setLogoInfo] = useState({})

    const [cropperVisible, setCropperVisible] = useState(false)
    const [coverImg, setCoverImg] = useState(null)
    const [file, setFile] = useState(null)
    //上传函数
    const uploadLogo = (res) => {
        let formData = new FormData()
        formData.append("file", res.file)
        formData.append("schoolId", sessionStorage.getItem("schoolId"))
        $.ajax({
            url: BasicProxy + "/file",
            type: "post",
            data: formData,
            async: true,
            dataType: 'json',
            headers: {
                Authorization: sessionStorage.getItem("token")
            },
            cache: false, // 上传文件无需缓存
            processData: false, // 使数据不做处理
            contentType: false, //不额外设置请求头
            success: function (res) {
                if (res.code == 200 && res.data) {
                    setLogoInfo(res.data)
                } else {
                    message.error(res.msg)
                }
            },
            error: function (res) {
                message.error("上传失败")
            }
        })
        //替换之前先释放上一个URL对象，否则造成内存占用
        // if(logoInfo.url){
        //     window.URL.revokeObjectURL(logoInfo.url);
        // }
        // let url = window.URL.createObjectURL(res.file);
        // typeof getVal === "function" &&
        // getVal({url, file: res.file});
        // setLogoInfo({url, file: res.file});
    }
    const getFile = (file, fileObj, base64) => {
        // setCoverImg(base64)
        let formData = new FormData()
        formData.append("file", file)
        formData.append("schoolId", sessionStorage.getItem("schoolId"))
        let url = BasicProxy + "/file"
        $.ajax({
            url,
            headers: {
                'Authorization': sessionStorage.getItem("token")
            },
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: (res) => {
                if (res.code == 200 && res.data) {
                    setLogoInfo(res.data)
                } else {
                    message.error(res.msg)
                }
            }
        })

    }
    const deleteImage = (e) => {
        e.stopPropagation()
        setLogoInfo({})
    }
    //写着玩的下载函数，回顾一下createObjectURL,和readAsDataURL的用法
    const download = () => {
        //1、createObjectURL()
        // let a = document.createElement("a");
        // a.href = logoInfo.url;
        // a.download = logoInfo.file.name;
        // let event = document.createEvent("MouseEvent");
        // event.initMouseEvent("click");
        // a.dispatchEvent(event);

        //2、readAsDataURL()
        let reader = new FileReader()
        if (!logoInfo.file) {
            return
        }
        reader.readAsDataURL(logoInfo.file)
        reader.onload = function (e) {
            let res = e.currentTarget.result
            let a = document.createElement("a")
            a.href = res
            a.download = logoInfo.file.name
            let event = document.createEvent("MouseEvent")
            event.initMouseEvent("click")
            a.dispatchEvent(event)
        }
    }
    const prevFile = (data) => {
        data.src = data.previewPath
        window.changePrevInfo(data)
    }
    const beforeImageUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
        if (!isJpgOrPng) {
            message.warn("只可以上传图片！")
        }
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!isLt2M) {
            message.error('图片大小不能超过10mb！')
        }
        return isJpgOrPng && isLt2M
    }
    const showCropper = (e) => {
        e.preventDefault()
        setCropperVisible(true)
    }
    useEffect(() => {
        typeof getVal === "function" &&
            getVal(logoInfo)
    }, [logoInfo])
    useLayoutEffect(() => {
        if (typeof value === "object" && value.id) {
            setLogoInfo(value)
        }

    }, [])
    return (
        <div className={`info_option ${className ? className : ""}`} style={{ marginTop: 2 }}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            {/* <Upload
        accept=".jpg,.png,.jpeg"
        className="option_logo"
        beforeUpload={beforeImageUpload}
        showUploadList={false}
        maxCount={1}
        disabled={disabled}
        customRequest={uploadLogo}> */}
            {
                typeof value === "object" && value.id ?
                    <div className="show_image" style={{
                        backgroundImage: `url('${value.server + value.relativePath}')`
                    }} onClick={showCropper}><i className="closelogo" onClick={deleteImage}></i></div> :
                    logoInfo.id ?
                        <div className="show_image" style={{
                            backgroundImage: `url('${logoInfo.server + logoInfo.relativePath}')`
                        }} onClick={showCropper}><i className="closelogo" onClick={deleteImage}></i></div> :
                        <div className={`upload_logo_btn ${disabled ? "disabled" : ""}`} onClick={showCropper}></div>
            }
            {/* </Upload> */}
            <Cropper
                visible={cropperVisible}
                getFile={(f, o, b) => getFile(f, o, b)}
                // imgUrl={typeof value === "object"? value.server + value.relativePath: logoInfo.server + logoInfo.relativePath} 
                onClose={() => setCropperVisible(false)} />
        </div>
    )
}
//上传图片
function OptionImage (props) {
    let {
        className,
        optionName,
        value,
        getVal,
        maxLength,
        disabled,
        optional
    } = props
    const [imageList, setImageList] = useState([])
    //上传函数
    const uploadImage = (res) => {
        let formData = new FormData()
        formData.append("file", res.file)
        formData.append("schoolId", sessionStorage.getItem("schoolId"))
        $.ajax({
            url: BasicProxy + "/file",
            type: "post",
            data: formData,
            async: true,
            dataType: 'json',
            headers: {
                Authorization: sessionStorage.getItem("token")
            },
            cache: false, // 上传文件无需缓存
            processData: false, // 使数据不做处理
            contentType: false, //不额外设置请求头
            success: function (res) {
                if (res.code == 200 && res.data) {
                    let list = JSON.parse(JSON.stringify(imageList))
                    list.push(res.data)
                    setImageList(list)
                } else {
                    message.error(res.msg)
                }
            },
            error: function (res) {
                message.error("上传失败")
            }
        })
    }
    const prevFile = (data, list) => {
        data.src = data.previewPath
        window.changePrevInfo(data, list)
    }
    const deleteImage = (index, e) => {
        e.stopPropagation()
        let list = JSON.parse(JSON.stringify(imageList))
        list.splice(index, 1)
        setImageList(list)
    }
    const beforeImageUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
        if (!isJpgOrPng) {
            message.warn("只可以上传图片！")
        }
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!isLt2M) {
            message.error('图片大小不能超过10mb！')
        }
        return isJpgOrPng && isLt2M
    }
    useLayoutEffect(() => {
        typeof getVal === "function" &&
            getVal(imageList)
    }, [imageList])
    useLayoutEffect(() => {
        if (Array.isArray(value)) {
            setImageList(value)
        }
    }, [])
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "red" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            {
                Array.isArray(value) &&
                    value.length > 0 ?
                    value.map((item, index) => {
                        return (
                            <div className="image_one" style={{
                                backgroundImage: `url('${item.server + item.relativePath}')`
                            }} key={index} onClick={() => prevFile(item, value)}><i className="closelogo" onClick={(e) => deleteImage(index, e)}></i></div>
                        )
                    }) :
                    imageList.map((item, index) => {
                        return (
                            <div className="image_one" style={{
                                backgroundImage: `url('${item.server + item.relativePath}')`
                            }} key={index} onClick={() => prevFile(item, imageList)}><i className="closelogo" onClick={(e) => deleteImage(index, e)}></i></div>
                        )
                    })
            }
            {
                maxLength ?
                    imageList.length >= maxLength ?
                        "" :
                        <Upload
                            accept=".jpg,.png,.jpeg"
                            className="option_image"
                            showUploadList={false}
                            maxCount={3}
                            multiple={true}
                            disabled={disabled}
                            beforeUpload={beforeImageUpload}
                            customRequest={uploadImage}>
                            <div className={`upload_image_btn ${disabled ? "disabled" : ""}`}></div>
                        </Upload> :
                    imageList.length >= 3 ?
                        "" :
                        <Upload
                            accept=".jpg,.png,.jpeg"
                            className="option_image"
                            showUploadList={false}
                            disabled={disabled}
                            beforeUpload={beforeImageUpload}
                            maxCount={3}
                            multiple={true}
                            customRequest={uploadImage}>
                            <div className={`upload_image_btn ${disabled ? "disabled" : ""}`}></div>
                        </Upload>
            }

        </div>
    )
}
//上传文件
function OptionFile (props) {
    let {
        className,
        optionName,
        value,
        getVal,
        maxLength,
        disabled,
        optional
    } = props
    const [fileList, setFileList] = useState([])
    //上传函数
    const uploadFile = (res) => {
        let formData = new FormData()
        formData.append("file", res.file)
        formData.append("schoolId", sessionStorage.getItem("schoolId"))
        $.ajax({
            url: BasicProxy + "/file",
            type: "post",
            data: formData,
            async: true,
            dataType: 'json',
            headers: {
                Authorization: sessionStorage.getItem("token")
            },
            cache: false, // 上传文件无需缓存
            processData: false, // 使数据不做处理
            contentType: false, //不额外设置请求头
            success: function (res) {
                if (res.code == 200 && res.data) {
                    let list = JSON.parse(JSON.stringify(fileList))
                    list.push(res.data)
                    setFileList(list)
                } else {
                    message.error(res.msg)
                }
            },
            error: function (res) {
                message.error("上传失败")
            }
        })
    }
    const deleteFile = (index) => {
        let list = JSON.parse(JSON.stringify(fileList))
        list.splice(index, 1)
        setFileList(list)
    }
    const prevFile = (data, list) => {
        data.src = data.previewPath
        window.changePrevInfo(data, list)
    }
    useLayoutEffect(() => {
        typeof getVal === "function" &&
            getVal(fileList)
    }, [fileList])
    useLayoutEffect(() => {
        if (Array.isArray(value)) {
            setFileList(value)
        }
    }, [])
    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' ||
            file.type === 'image/jpg' || file.type === "application/msword" ||
            file.type === "application/vnd.ms-excel" || file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
            file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
            file.type === "application/pdf"
        if (!isJpgOrPng) {
            message.warn("不支持上传该格式的文件！")
        }
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!isLt2M) {
            message.error('图片大小不能超过10mb！')
        }
        return isJpgOrPng && isLt2M
    }
    return (
        <div className={`info_option ${className ? className : ""}`}>
            <span className="option_name">
                <span style={{ color: "#ff00000" }}>{optional ? "*" : ""}</span>
                {optionName}:
            </span>
            <div className="file_container">
                {
                    disabled ?
                        <div>
                            <div className="disabled_file_btn">
                                上传文件
                            </div>
                            <span className="upload_tip_text">(上传文件大小不能超过10mb)</span>
                        </div> :
                        maxLength ?
                            fileList.length >= maxLength ?
                                <div>
                                    <div className="disabled_file_btn">
                                        上传文件
                                    </div>
                                    <span className="upload_tip_text">(上传文件大小不能超过10mb)</span>
                                </div> :
                                <Upload
                                    accept=".jpg,.png,.jpeg,.doc,.docx,.xls,.xlsx,.pdf"
                                    className="option_file"
                                    showUploadList={false}
                                    maxCount={3}
                                    multiple={false}
                                    beforeUpload={beforeUpload}
                                    customRequest={uploadFile}>
                                    <div>
                                        <div className="upload_file_btn">
                                            上传文件
                                        </div>
                                        <span className="upload_tip_text">(上传文件大小不能超过10mb)</span>
                                    </div>

                                </Upload> :
                            fileList.length >= 3 ?
                                <div>
                                    <div className="disabled_file_btn">
                                        上传文件
                                    </div>
                                    <span className="upload_tip_text">(上传文件大小不能超过10mb)</span>
                                </div> :
                                <Upload
                                    accept=".jpg,.png,.jpeg,.doc,.docx,.xls,.xlsx,.pdf"
                                    className="option_file"
                                    showUploadList={false}
                                    maxCount={3}
                                    multiple={true}
                                    beforeUpload={beforeUpload}
                                    customRequest={uploadFile}>
                                    <div>
                                        <div className="upload_file_btn">
                                            上传文件
                                        </div>
                                        <span className="upload_tip_text">(上传文件大小不能超过10mb)</span>
                                    </div>
                                </Upload>
                }
                {
                    Array.isArray(value) &&
                        value.length > 0 ?
                        value.map((item, index) => {
                            return (
                                <div className="file_one" key={index} title={item.fileName}>
                                    <i className={`filelogo ${fileIcon(item.fileName)}`}></i>
                                    <span onClick={() => prevFile(item, fileList)}>{item.fileName.length > 28 ? item.fileName.substr(0, 28) + "..." : item.fileName}</span>
                                    <i className="deletelogo" onClick={() => deleteFile(index)}></i>
                                </div>
                            )
                        }) :
                        fileList.map((item, index) => {
                            return (
                                <div className="file_one" key={index} title={item.fileName}>
                                    <i className={`filelogo ${fileIcon(item.fileName)}`}></i>
                                    <span onClick={() => prevFile(item, fileList)}>{item.fileName.length > 28 ? item.fileName.substr(0, 28) + "..." : item.fileName}</span>
                                    <i className="deletelogo" onClick={() => deleteFile(index)}></i>
                                </div>
                            )
                        })
                }
            </div>
        </div>
    )
}
export default ModalOption
